package VideoProcessing;

import java.awt.Dimension;
import java.awt.image.WritableRaster;

import javax.media.format.VideoFormat;

import Util.Constants;

public class LowerResolution extends RgbVideoEffect {
	private static final int FILTER_SIZE = Constants.RESOLUTION_BLOCK_SIZE;

	@Override
	protected boolean processRGB(byte[] bin, byte[] bout, VideoFormat format) {
		Dimension size = format.getSize();

		for (int y = 0; y < size.height; y += FILTER_SIZE) {
			for (int x = 0; x < size.width; x += FILTER_SIZE) {
				int sum = 0, count = 0;
				int tx, ty;
				for (int ox = 0; ox < FILTER_SIZE; ox++) {
					for (int oy = 0; oy < FILTER_SIZE; oy++) {
						tx = x + ox;
						ty = y + oy;
						if (inBoundry(tx, ty, size.width, size.height)) {
							sum += byte2Int(bin[(ty * size.width + tx)]);
							count++;
						}
					}
				}
				if (count != 0) {
					int avg = sum / count;
					for (int ox = 0; ox < FILTER_SIZE; ox++) {
						for (int oy = 0; oy < FILTER_SIZE; oy++) {
							tx = x + ox;
							ty = y + oy;
							if (inBoundry(tx, ty, size.width, size.height)) {
								bout[(ty * size.width + tx)] = (byte) avg;
							}
						}
					}
				} 
 			}
		}

		return true;
	}

	private boolean inBoundry(int tx, int ty, int width, int height) {
		return (0 <= tx && tx < width) && (0 <= ty && ty < height);
	}

	@Override
	public String getName() {
		return "Lower Resolution";
	}

	protected void updateImage(byte[] bout, VideoFormat vformat) {
		synchronized (displayImage) {
			// // Copy pixels to image
			WritableRaster rast = displayImage.getRaster();
			int[] pixel = new int[] { 0, 0, 0, 255 };
			int p = 0;
			for (int y = vformat.getSize().height - 1; y >= 0; y--) {
				for (int x = 0; x < vformat.getSize().width; x++) {
					pixel[0] = pixel[1] = pixel[2] = bout[p++];
					rast.setPixel(x, y, pixel);
				}
			}
		}
	}
}
